{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对分析的线性回归模型，设参数a、b、c、d分别表示截距、Sepal.Length、Sepal.Width、Petal.Length的系数\n",
    "\n",
    "将参数值范围设定在[-1，1]内，进行网格搜索"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.03607966942148759"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "iris = pd.read_csv(\"http://image.cador.cn/data/iris.csv\")\n",
    "x1 = iris.loc[:,['Sepal.Length']].values\n",
    "x2 = iris.loc[:,['Sepal.Width']].values\n",
    "x3 = iris.loc[:,['Petal.Length']].values\n",
    "y = iris.loc[:,['Petal.Width']].values\n",
    "\n",
    "minMSE=1000\n",
    "k=55\n",
    "for a in range(k+1):\n",
    "    for b in range(k+1):\n",
    "        for c in range(k+1):\n",
    "            for d in range(k+1):\n",
    "                a0 = 2.0*a/k -1\n",
    "                b0 = 2.0*b/k -1\n",
    "                c0 = 2.0*c/k -1\n",
    "                d0 = 2.0*d/k -1\n",
    "                y0 = a0 + b0*x1 + c0*x2 + d0*x3\n",
    "                mse = np.mean((y-y0)**2)\n",
    "                if mse < minMSE:\n",
    "                    minMSE = mse\n",
    "                    f_a0 = a0\n",
    "                    f_b0 = b0\n",
    "                    f_c0 = c0\n",
    "                    f_d0 = d0\n",
    "\n",
    "minMSE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(-0.34545454545454546,\n",
       " -0.19999999999999996,\n",
       " 0.23636363636363633,\n",
       " 0.5272727272727273)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f_a0,f_b0,f_c0,f_d0"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
